package com.jplus.framework.mvc.handler;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jplus.framework.AppConstant;
import com.jplus.framework.bean.annotation.Component;
import com.jplus.framework.mvc.bean.Result;
import com.jplus.framework.mvc.bean.View;
import com.jplus.framework.util.FormatUtil;
import com.jplus.framework.util.WebUtil;

/**
 * 默认视图解析器[单例]
 *
 * @author huangyong
 * @author Yuanqy
 */
@Component
public class ViewResolver {

	public void resolveView(HttpServletRequest request, HttpServletResponse response, Object actionMethodResult) {
		if (actionMethodResult != null) {
			// Action 返回值可为 View 或 Result
			if (actionMethodResult instanceof View) {
				// 若为 View，则需考虑两种视图类型（重定向 或 转发）
				View view = (View) actionMethodResult;
				if (FormatUtil.isEmpty(view.getPath()))// 设置默认值[默认就是请求url]
					view.setPath(WebUtil.getRequestPath(request));

				if (view.isRedirect()) {
					// 获取路径
					String path = view.getPath();
					// 重定向请求
					WebUtil.redirectRequest(path, request, response);
				} else {
					// 获取路径
					String path = AppConstant.CONFIG.AppViewPath.getValue() + view.getPath();
					if (!path.endsWith(AppConstant.CONFIG.AppViewSuffix.getValue()))
						path += AppConstant.CONFIG.AppViewSuffix.getValue();
					// 初始化请求属性
					Map<String, Object> data = view.getData();
					if (data != null && data.size() > 0) {
						for (Map.Entry<String, Object> entry : data.entrySet()) {
							request.setAttribute(entry.getKey(), entry.getValue());
						}
					}
					// 转发请求
					WebUtil.forwardRequest(path, request, response);
				}
			} else if (actionMethodResult instanceof Result) {
				Result result = (Result) actionMethodResult;
				WebUtil.writeJSON(response, result);
			} else {
				// 若为其他，，统统转json
				WebUtil.writeJSON(response, actionMethodResult);
			}
		}
	}
}
